package com.fcat.common.user.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.fcat.common.user.constant.UserConstant;
import com.fcat.common.user.enums.StateCode;
import com.fcat.springboot.core.util.SpringbootUtil;
import com.fcat.springboot.mybatis.controller.TsuantoneBaseController;
import com.fcat.base.common.util.ArrayUtil;
import com.fcat.springboot.mybatis.util.JsonUtil;
import com.fcat.base.common.util.StrUtil;
import com.fcat.common.user.config.Constants;
import com.fcat.common.user.entity.User;
import com.fcat.common.user.entity.UserRole;
import com.fcat.common.user.rpc.IJDService;
import com.fcat.common.user.service.KeycloakService;
import com.fcat.common.user.service.OrganizationService;
import com.fcat.common.user.service.UserRoleService;
import com.fcat.common.user.service.UserService;
import com.fcat.common.user.vo.UserVO;
import com.fcat.springboot.redis.service.RedisService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController extends TsuantoneBaseController<UserService, User, Integer> {

    @Autowired
    private OrganizationService organizationService;

    @Autowired
    private RedisService redisService;
    @Autowired
    private UserService userService;
    @Autowired
    private KeycloakService keycloakService;

    @Value("${token.realm}")
    private String realm;
    @Value("${token.client}")
    private String client;
    @Value("${token.clientSecret}")
    private String clientSecret;
    @Value("${token.clienId}")
    private String clienId;

    @ApiOperation("添加用户")
    @PostMapping("/addUser")
    public JSONObject addUser( @RequestBody JSONObject jsonObject) {
        jsonObject.put("isCheckPass", 1);
        //因为需要添加事务所以所有放入service处理
        return bsi.addUser(SpringbootUtil.getCurrentToken(), jsonObject);
    }


    @ApiOperation("注册用户")
    @PostMapping("/registerUser")
    public JSONObject registerUser(@RequestBody JSONObject jsonObject) {
        JSONObject res = bsi.registerUser(jsonObject);
        return res;
    }

    @ApiOperation("账户设置")
    @PostMapping("/updateUser")
    public JSONObject updateUser(@RequestBody JSONObject jsonObject) {
        return bsi.updateUser(SpringbootUtil.getCurrentToken(), jsonObject);
    }


    @ApiOperation("查询用户列表")
    @GetMapping("/getListByOrganizationId")
    public JSONObject getListByOrganizationId(@RequestParam("organizationId") Long organizationId,
                                              @RequestParam(value = "pageNo", defaultValue = "1", required = true) Integer pageNo,
                                              @RequestParam(value = "pageSize", defaultValue = "15", required = true) Integer pageSize) {
        if (organizationId == null) return JsonUtil.getFailJsonObject("请选择组织");
        List<Long> longs = organizationService.getIdsByPrentId(organizationId);
        PageHelper.startPage(pageNo, pageSize);
        Map<String, Object> map = new HashMap<>();
        map.put("list", longs);
        List<UserVO> userVOList = bsi.getListByOrganizationId(map);
        PageInfo pageInfo = new PageInfo(userVOList);
        if (ArrayUtil.isEmpty(userVOList)) return JsonUtil.getSuccessJsonObject(new JSONArray());
        JSONObject result = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        for (UserVO vo : userVOList) {
            JSONObject item = new JSONObject();
            item.put("id", vo.getId());
            item.put("name", vo.getName());
            item.put("sex", vo.getSex());
            item.put("certificateCode", vo.getCertificateCode());
            item.put("organizationName", vo.getOrganizationName());
            item.put("roleMaps", vo.getRoleMaps());
            item.put("cellNumber", vo.getCellNumber());
            item.put("username", vo.getUsername());
            item.put("position", vo.getPosition());
            item.put("email", vo.getEmail());
            item.put("loginStatus", StrUtil.isBlank(redisService.getStringValue(vo.getUsername())) ? 0 : 1);
            jsonArray.add(item);
        }
        result.put("list", jsonArray);
        result.put("total", pageInfo.getTotal());
        result.put("pageCount", pageInfo.getPages());
        return JsonUtil.getSuccessJsonObject(result);
    }


    @ApiOperation("查看用户信息")
    @GetMapping("/getByUsername")
    public JSONObject getByUsername(@RequestParam(value = "queryusername", required = false) String queryusername) {
        String tmp = queryusername;
        if (StrUtil.isBlank(queryusername)) {//查询的username，如果不存在，则查询当前登陆 用户
            tmp = SpringbootUtil.parseToken().getUsername();
        }
        Map<String, Object> map = new HashMap<>();
        map.put("username", tmp);
        UserVO userVO = bsi.getUserVOByUsername(map);
        return JsonUtil.getSuccessJsonObject(userVO);

    }

    @ApiOperation("根据用户id查看用户信息")
    @GetMapping("/getById")
    public JSONObject getById(@RequestParam(value = "id", required = false) Long id) {
        if (id == null) return JsonUtil.getFailJsonObject("请选择用户");
        Map<String, Object> map = new HashMap<>();
        map.put("id", id);
        UserVO userVO = bsi.getUserVOById(map);
        return JsonUtil.getSuccessJsonObject(userVO);

    }

    @ApiOperation("删除用户")
    @PostMapping("delUser")
    public JSONObject delUser( @RequestParam("username") String username) {
        User user=bsi.getUserByUsername(username);
        if(user!=null && user.getKeycloakId()!=null){
            return bsi.delUserByKeycloakId(SpringbootUtil.getCurrentToken(), user);
        }
        return JsonUtil.getFailJsonObject("该用户不存在");
    }


    @ApiOperation("删除用户")
    @PostMapping("delUserById")
    public JSONObject delUserById( @RequestParam("id") Long id) {
        User user=bsi.selectById(id);
        if(user!=null && user.getKeycloakId()!=null){
            return bsi.delUserByKeycloakId(SpringbootUtil.getCurrentToken(), user);
        }
        return JsonUtil.getFailJsonObject("该用户不存在");
    }


    @ApiOperation("根据单位名称电话姓名查询用信息")
    @GetMapping("getListByLike")
    public JSONObject getListByLike(@RequestParam("companyName") String companyName, @RequestParam("unitCategory") String unitCategory, String keyword) {
        if (StrUtil.isBlank(unitCategory)) return JsonUtil.getFailJsonObject("请先单位类别");
        if (StrUtil.isBlank(companyName)) return JsonUtil.getFailJsonObject("请先输入单位名称");
//        if (StrUtil.isBlank(keyword)) return JsonUtil.getFailJsonObject("请输入姓名或者电话号码");
        Map<String, Object> map = new HashMap<>();
        map.put("companyName", companyName);
        map.put("unitCategory", unitCategory);
        map.put("keyword", keyword);
        List<UserVO> userVOList = bsi.getListByLike(map);
        if (ArrayUtil.isEmpty(userVOList)) return JsonUtil.getSuccessJsonObject(new JSONArray());
        JSONArray jsonArray = new JSONArray();
        for (UserVO vo : userVOList) {
            JSONObject item = new JSONObject();
            item.put("id", vo.getId());
            item.put("unitCategory", vo.getCompanyUnitCategory());
            item.put("companyName", vo.getCompanyName());
            item.put("headPicture", vo.getHeadPicture());
            item.put("name", vo.getName());
            item.put("username", vo.getUsername());
            jsonArray.add(item);
        }
        return JsonUtil.getSuccessJsonObject(jsonArray);
    }

    private final String jdKey = "2beb869409923234222c9c2687c9e103";

    @Resource
    private IJDService ijdService;

    @ApiOperation("获取天气")
    @GetMapping("getWeather")
    public JSONObject getWeather(@RequestParam("city") String city) {
        JSONObject jsonObject = ijdService.getWeather(city, jdKey);
        String code = jsonObject.getString("code");
        if ("10000".equals(code)) {
            return JsonUtil.getSuccessJsonObject(jsonObject.getJSONObject("result"));
        }
        return JsonUtil.getFailJsonObject("获取天气失败");
    }


    @ApiOperation("redis测试")
    @GetMapping("/redisGetTest")
    public JSONObject redisGetTest(@RequestParam("key") String key) {
        return JsonUtil.getSuccessJsonObject(redisService.getValue(key));
    }

    @GetMapping("test22")
    public JSONObject test22(){
        User u3=new User();
        u3.setName("11");
        u3.setUsername("123");
        User u2=new User();
        u2.setName("22");
        u2.setUsername("33");
        List<User> list = new ArrayList<>();
        list.add(u3);
        list.add(u2);
        bsi.insertList(list);
        return JsonUtil.getSuccessJsonObject();
    }

    @Autowired
    UserRoleService userRoleService;

    @GetMapping("test444")
    public JSONObject test44(){
        UserRole u3=new UserRole();
        u3.setRoleId(1L);
        u3.setUserId(5L);
        UserRole u2=new UserRole();
        u2.setRoleId(7L);
        u2.setUserId(4L);
        List<UserRole> list = new ArrayList<>();
        list.add(u3);
        list.add(u2);

        System.out.println("插入前"+JSONObject.toJSONString(list));
        userRoleService.insertList(list);
        System.out.println("插入后"+JSONObject.toJSONString(list));
        u2.setUserId(7L);
        userRoleService.batchUpdateById(list);
        System.out.println("更新后"+JSONObject.toJSONString(list));
        List<Long> ids = new ArrayList<>();
        ids.add(u2.getId());
        ids.add(u3.getId());
        userRoleService.deleteByIds(ids);
        return JsonUtil.getSuccessJsonObject(list);
    }


    /**
     * 重置密码
     *
     * @return
     */
    @ApiOperation(value = "修改密码", notes = "返回成功或失败,")
    @RequestMapping(value = "/updatePassword", method = RequestMethod.POST)
    public JSONObject updatePassword(@RequestParam("username") String username,
                                     @RequestParam("password") String password) {
        return keycloakService.updatePassword(SpringbootUtil.getCurrentToken(),username,password);
    }

    @ApiOperation(value = "修改密码", notes = "返回成功或失败,")
    @RequestMapping(value = "/updatePasswordWithOld", method = RequestMethod.POST)
    public JSONObject updatePasswordWithOld(@RequestBody JSONObject jsonObject) {

        String username =jsonObject.getString("username");
        String oldPassword =jsonObject.getString("oldPassword");
        String newPassword =jsonObject.getString("newPassword");
        if(StrUtil.isEmpty(username)){
            return JsonUtil.getFailJsonObject("账号不能为空");
        }
        if(StrUtil.isEmpty(oldPassword)){
            return JsonUtil.getFailJsonObject("旧密码不能为空");
        }
        if(StrUtil.isEmpty(newPassword)){
            return JsonUtil.getFailJsonObject("新密码不能为空");
        }

        //先检验旧密码是否有效
        JSONObject paramObj = new JSONObject();
        JSONObject attributesObj = new JSONObject();
        username=username.toLowerCase();
        attributesObj.put("mac", "");
        paramObj.put("realm", realm);
        paramObj.put("client", client);
        paramObj.put("username", username);
        paramObj.put("password", oldPassword);
        paramObj.put("clientSecret", clientSecret);
        paramObj.put("attributes", attributesObj);
        User tmp = new User();
        tmp.setUsername(username);
        //先查找该用户是否在系统中存在
        User user = userService.selectOne(tmp);
        if (user == null || user.getDeleteFlag())
            return JsonUtil.getFailJsonObject(StateCode.ERROR_CHECK_PASSWORD_FAILED.getCode(),StateCode.ERROR_CHECK_PASSWORD_FAILED.getMsg());
        if (!user.getIsCheckPass()) return JsonUtil.getFailJsonObject("当前账户未审核");
        JSONObject resultJsonObject=keycloakService.token(paramObj);
        int code = resultJsonObject.getIntValue("code");
        if(code==-401){
            return JsonUtil.getFailJsonObject(StateCode.ERROR_OLD_PASSWORD_FAILED.getCode(),StateCode.ERROR_OLD_PASSWORD_FAILED.getMsg());
        }
        return keycloakService.updatePassword(SpringbootUtil.getCurrentToken(),username,newPassword);
    }






//
    @GetMapping("test555")
    public JSONObject test555(String token){
        return keycloakService.getResources("dcc");
    }




}